require 'rbof'

class App < OF::SimpleApp
  include OF
  
  def setup
    background 0, 0, 0
    setColor 0xFFFFFF
    
    @phase = 0
  	@phase_adder = 0
  	@phase_adder_target = 0
  	
  	buff_size = 1024
  	@audio = Array.new buff_size, 0
    soundStreamSetup 1, 0, self, 44100, buff_size, 4
  end
  
  def draw
    drawBitmapString "move your mouse or click to make a noise", 20, 40
    400.times do |i|
      line i, 200, i, 200 + @audio[i] * 500.0
    end
  end
  
  def mouseMoved(x, y)
    height = 1 - y.to_f / getHeight
  	freq = 2000.0 * height
  	@phase_adder_target = (freq / 44100) * TWO_PI
  end
  
  def mousePressed(x, y, button)
    @pressed = true
  end
  
  def mouseReleased 
    @pressed = false
  end
  
  def audioRequested(buff, size, channels)
    volume = 0.1
    
    if @pressed
      buff.map! {randomf * volume}
    else
      @phase_adder = 0.95 * @phase_adder + 0.05 * @phase_adder_target
      buff.length.times do |i|
        @phase += @phase_adder
        buff[i] = Math.sin(@phase) * volume
      end
    end
    @audio = buff
  end
end

OF.setupOpenGL 400, 400, OF::WINDOW
OF.runApp App.new
